#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include "FTHeader.h"
#include "serverTask.h"
#include "TCPUtils.h"

#define MAX_REQUEST_SIZE 256

void serverLoop(int new_fd) {
	FTHeader *header;
	int index;

	header = createFTHeader(MAX_REQUEST_SIZE);
	if (header == NULL) {
		return;
	}
	//todo 接收响应的处理
        // todo ......

	for (index = 0; workers[index].method != NULL; ++index) {
		if (check_request(header, workers[index].method)) {
			break;
		}
	}
	if (workers[index].method == NULL) {
		fprintf(stderr, "Not valid request!\n");
		return;
	}
	workers[index].worker_handler(new_fd, header);

	releaseFTHeader(header);
}

int main(int argc, char *argv[]) {
	int new_fd;
	if (argc != 2) {
		fprintf(stderr, "please usage: server port!\n");
		return -1;
	}

	// 解析argv[1]指向的字符串，转换为uint16_t值
	char *endpoint;					// 存储转换结束的空间地址
	uint16_t port = strtol(argv[1], &endpoint, 10);
	if (*endpoint != '\0') {		// 正常全部转换后，指向字符串空间的0位置
		fprintf(stderr, "convert failed!\n");
		return -1;
	}

	int listen_fd = initTCPServer(port);		// 初始化了监听描述符
	if (listen_fd < 0) {
		fprintf(stderr, "initTCPServer error!\n");
		return -1;
	}
	printf("listening...\n");
	while (1) {
		new_fd = accept(listen_fd, NULL, NULL);
		if (new_fd < 0) {
			perror("accept");
			break;
		}
		printf("Have a new connection!\n");
		serverLoop(new_fd);
		close(new_fd);
	}
	close(listen_fd);
	return 0;
}